<template>
  <div class="dice-container">
    <!-- 骰子显示区域 -->
    <div class="dice-wrapper">
      <div 
        class="dice" 
        :class="{ 
          rolling: isRolling, 
          'show-result': !isRolling && currentResult 
        }"
        @click="rollDice"
      >
        <div class="dice-face" v-if="currentResult">
          <img 
            :src="getDiceImage(currentResult)" 
            :alt="`骰子 ${currentResult} 点`"
            class="dice-image"
          />
        </div>
        <div v-else class="dice-icon">🎲</div>
      </div>
    </div>

    <!-- 控制按钮 -->
    <div class="controls">
      <button 
        @click="rollDice" 
        :disabled="isRolling"
        class="roll-button"
      >
        {{ isRolling ? '掷骰中...' : '掷骰子' }}
      </button>
      <button 
        @click="resetDice" 
        :disabled="isRolling"
        class="reset-button"
      >
        重置
      </button>
    </div>

    <!-- 结果显示 -->
    <div v-if="currentResult && !isRolling" class="result-display">
      结果：{{ currentResult }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 导入骰子图片
import dice1 from '../assets/dice/1.jpg'
import dice2 from '../assets/dice/2.jpg'
import dice3 from '../assets/dice/3.jpg'
import dice4 from '../assets/dice/4.jpg'
import dice5 from '../assets/dice/5.jpg'
import dice6 from '../assets/dice/6.jpg'

const emit = defineEmits<{
  (e: 'rolled', value: number): void
}>()

const isRolling = ref(false)
const currentResult = ref<number | null>(null)
const audioContext = ref<AudioContext | null>(null)
const audioBuffer = ref<AudioBuffer | null>(null)

// 骰子图片映射
const diceImages = {
  1: dice1,
  2: dice2,
  3: dice3,
  4: dice4,
  5: dice5,
  6: dice6
}

function getDiceImage(value: number): string {
  return diceImages[value as keyof typeof diceImages]
}

// 初始化音频
async function initAudio() {
  try {
    audioContext.value = new (window.AudioContext || (window as any).webkitAudioContext)()
    
    // 尝试加载音频文件
    const audioPath = '/dice-sound.mp3' // 音频文件路径
    const response = await fetch(audioPath)
    if (response.ok) {
      const arrayBuffer = await response.arrayBuffer()
      audioBuffer.value = await audioContext.value.decodeAudioData(arrayBuffer)
    }
  } catch (error) {
    console.log('音频加载失败，将使用默认音效:', error)
  }
}

// 播放音效
function playSound() {
  if (audioContext.value && audioBuffer.value) {
    try {
      const source = audioContext.value.createBufferSource()
      source.buffer = audioBuffer.value
      source.connect(audioContext.value.destination)
      source.start()
    } catch (error) {
      console.log('音效播放失败:', error)
    }
  } else {
    // 如果没有音频文件，使用Web Audio API生成简单音效
    playDefaultSound()
  }
}

// 生成默认音效（骰子滚动声）
function playDefaultSound() {
  if (!audioContext.value) return
  
  try {
    const oscillator = audioContext.value.createOscillator()
    const gainNode = audioContext.value.createGain()
    
    oscillator.connect(gainNode)
    gainNode.connect(audioContext.value.destination)
    
    // 设置音效参数
    oscillator.frequency.setValueAtTime(200, audioContext.value.currentTime)
    oscillator.frequency.exponentialRampToValueAtTime(100, audioContext.value.currentTime + 0.3)
    
    gainNode.gain.setValueAtTime(0.3, audioContext.value.currentTime)
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.value.currentTime + 0.3)
    
    oscillator.start(audioContext.value.currentTime)
    oscillator.stop(audioContext.value.currentTime + 0.3)
  } catch (error) {
    console.log('默认音效播放失败:', error)
  }
}

onMounted(() => {
  initAudio()
})

function rollDice() {
  if (isRolling.value) return
  
  // 播放音效
  playSound()
  
  isRolling.value = true
  currentResult.value = null

  // 模拟摇晃动画，显示随机数字
  let rollCount = 0
  const maxRolls = 15
  const rollInterval = setInterval(() => {
    currentResult.value = Math.floor(Math.random() * 6) + 1
    rollCount++
    
    if (rollCount >= maxRolls) {
      clearInterval(rollInterval)
      
      // 最终结果
      const finalResult = Math.floor(Math.random() * 6) + 1
      currentResult.value = finalResult
      
      // 延迟一点时间让用户看到最终结果
      setTimeout(() => {
        isRolling.value = false
        emit('rolled', finalResult)
      }, 300)
    }
  }, 100)
}

function resetDice() {
  if (isRolling.value) return
  currentResult.value = null
}
</script>

<style scoped>
.dice-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  width: 100%;
  max-width: 500px;
  padding: 0 10px;
  flex-shrink: 0;
}

.dice-wrapper {
  perspective: 1000px;
  width: 100%;
  display: flex;
  justify-content: center;
}

.dice {
  width: 120px;
  height: 120px;
  background: linear-gradient(145deg, #ffffff, #f0f0f0);
  border: 3px solid #333;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 
    0 6px 12px rgba(0, 0, 0, 0.1),
    inset 0 2px 4px rgba(255, 255, 255, 0.8),
    inset 0 -2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  position: relative;
  transform-style: preserve-3d;
  flex-shrink: 0;
}

.dice:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 12px 24px rgba(0, 0, 0, 0.15),
    inset 0 2px 4px rgba(255, 255, 255, 0.8),
    inset 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.dice.rolling {
  animation: diceShake 0.1s infinite;
}

.dice.rolling .dice-image {
  animation: imageFlicker 0.1s infinite;
}

.dice.show-result {
  animation: diceLand 0.5s ease-out;
}

@keyframes diceShake {
  0%, 100% { 
    transform: rotate(0deg) translateY(0px);
  }
  10% { 
    transform: rotate(-5deg) translateY(-5px);
  }
  20% { 
    transform: rotate(5deg) translateY(5px);
  }
  30% { 
    transform: rotate(-3deg) translateY(-3px);
  }
  40% { 
    transform: rotate(3deg) translateY(3px);
  }
  50% { 
    transform: rotate(-2deg) translateY(-2px);
  }
  60% { 
    transform: rotate(2deg) translateY(2px);
  }
  70% { 
    transform: rotate(-1deg) translateY(-1px);
  }
  80% { 
    transform: rotate(1deg) translateY(1px);
  }
  90% { 
    transform: rotate(-0.5deg) translateY(-0.5px);
  }
}

@keyframes diceLand {
  0% { 
    transform: rotate(0deg) scale(1);
  }
  50% { 
    transform: rotate(5deg) scale(1.1);
  }
  100% { 
    transform: rotate(0deg) scale(1);
  }
}

@keyframes imageFlicker {
  0%, 100% { 
    opacity: 1;
    transform: scale(1);
  }
  50% { 
    opacity: 0.8;
    transform: scale(1.05);
  }
}

.dice-face {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border-radius: 16px;
}

.dice-icon {
  font-size: 48px;
}

.dice-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 16px;
  transition: all 0.3s ease;
}

.controls {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
  max-width: 400px;
}

.roll-button, .reset-button {
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 600;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-family: "Microsoft YaHei", sans-serif;
  flex: 1;
  min-width: 80px;
}

.roll-button {
  background: linear-gradient(145deg, #4CAF50, #45a049);
  color: white;
  box-shadow: 0 4px 8px rgba(76, 175, 80, 0.3);
}

.roll-button:hover:not(:disabled) {
  background: linear-gradient(145deg, #45a049, #3d8b40);
  transform: translateY(-1px);
  box-shadow: 0 6px 12px rgba(76, 175, 80, 0.4);
}

.roll-button:disabled {
  background: #ccc;
  cursor: not-allowed;
  box-shadow: none;
}

.reset-button {
  background: linear-gradient(145deg, #f44336, #da190b);
  color: white;
  box-shadow: 0 4px 8px rgba(244, 67, 54, 0.3);
}

.reset-button:hover:not(:disabled) {
  background: linear-gradient(145deg, #da190b, #c1170b);
  transform: translateY(-1px);
  box-shadow: 0 6px 12px rgba(244, 67, 54, 0.4);
}

.reset-button:disabled {
  background: #ccc;
  cursor: not-allowed;
  box-shadow: none;
}

.result-display {
  font-size: 20px;
  font-weight: bold;
  color: #2e7d32;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  animation: resultAppear 0.5s ease-out;
  margin-top: 5px;
}

@keyframes resultAppear {
  0% { 
    opacity: 0; 
    transform: scale(0.8) translateY(10px);
  }
  100% { 
    opacity: 1; 
    transform: scale(1) translateY(0);
  }
}

/* 手机端适配 */
@media (max-width: 768px) {
  .dice-container {
    gap: 12px;
    padding: 0 8px;
    max-width: 450px;
  }
  
  .dice {
    width: 100px;
    height: 100px;
    border-radius: 14px;
  }
  
  .dice-icon {
    font-size: 42px;
  }
  
  .controls {
    gap: 10px;
    max-width: 350px;
  }
  
  .roll-button, .reset-button {
    padding: 9px 18px;
    font-size: 13px;
  }
  
  .result-display {
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .dice-container {
    gap: 10px;
    padding: 0 5px;
    max-width: 400px;
  }
  
  .dice {
    width: 90px;
    height: 90px;
    border-radius: 12px;
  }
  
  .dice-icon {
    font-size: 38px;
  }
  
  .controls {
    gap: 8px;
    max-width: 300px;
  }
  
  .roll-button, .reset-button {
    padding: 8px 14px;
    font-size: 12px;
    min-width: 75px;
  }
  
  .result-display {
    font-size: 16px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 360px) {
  .dice-container {
    max-width: 350px;
  }
  
  .dice {
    width: 80px;
    height: 80px;
  }
  
  .dice-icon {
    font-size: 34px;
  }
  
  .controls {
    max-width: 280px;
  }
  
  .roll-button, .reset-button {
    padding: 6px 12px;
    font-size: 11px;
    min-width: 65px;
  }
}
</style>
